package com.yue92.datalife.helper;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.yue92.datalife.model.Moment;
import com.yue92.datalife.response.MomentRes;
import com.yue92.datalife.service.IMomentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class MomentHelper {

    @Autowired
    private IMomentService momentService;

    private Cache<String, List<Moment>> cache = CacheBuilder.newBuilder().expireAfterWrite(10, TimeUnit.MINUTES).build();

    public MomentRes index() {
        List<Moment> moments;
        try {
            moments = cache.get("moments", () -> momentService.findAll());
        } catch (ExecutionException e) {
            log.error(e.getMessage());
            moments = new ArrayList<>();
        }

        LocalDate nowDate = LocalDate.now();
        List<MomentRes.ItemRes> list = new ArrayList<>();
        long maxDays = 0L;
        for (Moment moment : moments) {

            long totalDays = ChronoUnit.DAYS.between(moment.getDate(), nowDate);
            Period period = Period.between(moment.getDate(), nowDate);
            if (totalDays > maxDays) {
                maxDays = totalDays;
            }

            list.add(MomentRes.ItemRes.builder()
                    .title(moment.getTitle())
                    .date(moment.getDate().toString())
                    .color(moment.getColor())
                    .durationDay(totalDays)
                    .durationFormat(String.format("%d years %d months %d days", period.getYears(), period.getMonths(), period.getDays()))
                    .build()
            );
        }

        return MomentRes.builder()
                .maxDurationDay(maxDays)
                .list(list)
                .build();
    }

}
